package com.shujia.flink.sql

import java.time.ZoneId

import org.apache.flink.streaming.api.scala.StreamExecutionEnvironment
import org.apache.flink.table.api.EnvironmentSettings
import org.apache.flink.table.api.bridge.scala.StreamTableEnvironment
import org.apache.flink.table.functions.{ScalarFunction, TableFunction}

object Demo9ProWindow {
  def main(args: Array[String]): Unit = {


    val bsEnv: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment

    val bsSettings: EnvironmentSettings = EnvironmentSettings
      .newInstance()
      .useBlinkPlanner() //使用blink计划器
      .inStreamingMode() //使用流模型
      .build()

    //创建flink sql的执行环境
    val bsTableEnv: StreamTableEnvironment = StreamTableEnvironment.create(bsEnv, bsSettings)


    bsTableEnv.executeSql(
      """
        |CREATE TABLE lines (
        | line STRING,
        | ts AS PROCTIME()
        |) WITH (
        | 'connector' = 'kafka',
        | 'topic' = 'lines',
        | 'properties.bootstrap.servers' = 'master:9092,node1:9092,node2:9092',
        | 'properties.group.id' = 'testGroup',
        | 'format' = 'csv',
        | 'scan.startup.mode' = 'earliest-offset',
        | 'csv.field-delimiter'='*'
        |)
        |
      """.stripMargin)


    bsTableEnv.executeSql(
      """
        |CREATE TABLE print_table
        | (
        | word STRING,
        | end_time STRING,
        | c BIGINT
        | )
        |WITH ('connector' = 'print')
        |
      """.stripMargin)


    /**
      * 注册自定义函数
      *
      */

    bsTableEnv.createTemporaryFunction("explode", classOf[Explode])
    bsTableEnv.createTemporaryFunction("addTime", classOf[addTime])

    /**
      * 每隔5秒统计单词的数量
      *
      */

    bsTableEnv.executeSql(
      """
        |insert into print_table
        |
        |
        |select
        |word,
        |DATE_FORMAT(addTime(TUMBLE_END(ts, INTERVAL '5' SECOND)),'yyyyMMddHHmmss') as end_time,
        |count(1) c
        |from
        |lines,lateral table(explode(line)) as t(word)
        |group by word,TUMBLE(ts, INTERVAL '5' SECOND)
        |
        |
      """.stripMargin)
  }

}

/**
  * 自定义UDTF
  *
  */
class Explode extends TableFunction[String] {
  def eval(line: String): Unit = {

    //将一行数据拆分成多行数据方式到下游
    line
      .split(",")
      .foreach(word => collect(word))

  }

}

import java.time.LocalDateTime

class addTime extends ScalarFunction {
  def eval(line: LocalDateTime): LocalDateTime = {
    //增加8小时
    line.plusHours(8)
  }
}